/**
 * Copyright (c) 2013 onionframework.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.onionframework.code.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.apache.commons.lang3.StringUtils;
import org.onionframework.code.CodeTools;
import org.onionframework.code.model.Code;
import org.onionframework.code.model.CodeType;
import org.onionframework.core.Onion;

/**
 * @author allan
 *
 */
@FacesConverter("onion.code.CodeConverter")
public class CodeConverter implements Converter{

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		
		if(StringUtils.isBlank(value))
			return null;
		else{
			return Onion.getBean(CodeTools.class).getCode(value, (CodeType)component.getAttributes().get("onion.code.CodeConverter.codeType"));
		}
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		try {
			if(value == null)
				return null;
			
			Code code = (Code)value;
			
			component.getAttributes().put("onion.code.CodeConverter.codeType", code.getType());
			
			return code.getValue();
			
		} catch (Exception e) {
			throw new ConverterException(e);
		}
	}

}
